package com.natalia.file.verify;

import org.apache.commons.io.FilenameUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.Arrays;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * @Author yang
 **/
public class MultipartFilesValidator implements ConstraintValidator<MultipartFileVerify, MultipartFile[]> {

    MultipartFileVerify multipartFileVerify;

    @Override
    public void initialize(MultipartFileVerify constraintAnnotation) {
        this.multipartFileVerify = constraintAnnotation;
    }

    @Override
    public boolean isValid(MultipartFile[] value, ConstraintValidatorContext context) {
        for (MultipartFile file : value) {
            if (FileValid.isFileInvalid(file, multipartFileVerify.maxSize(),context)){
                return false;
            }
            if (FileValid.isFileInvalid(file, multipartFileVerify.maxSize(),context)) {
                return false;
            }
        }
        return check(value);
    }

    /**
     * 判断文件类型是否符合规则
     */
    private boolean check(MultipartFile[] value){
        Set<String> validators = Arrays.stream(multipartFileVerify.value())
            .map(FileType::getName)
            .collect(Collectors.toSet());
        if(ObjectUtils.isEmpty(validators)){
            return true;
        }
        Set<String> requests = Arrays.stream(value)
                .map(multipartFile -> FilenameUtils.getExtension(multipartFile.getOriginalFilename()))
                .collect(Collectors.toSet());
        for (String request:requests) {
            if (!validators.contains(request)){
                return false;
            }
        }
        return true;
    }
}
